import { CaretDownOutlined, CaretUpOutlined, CloseCircleOutlined } from '@ant-design/icons';
import { Flex, message, Popconfirm, Spin, TabsProps } from 'antd';
import dayjs from 'dayjs';
import React, { useEffect, useRef, useState } from 'react';

import datasetService from '@/api/services/datasetService';
import knowService from '@/api/services/knowService';
import { AntdTabs, Button, Content, Search } from '@/components/eai-design';
import { SvgIcon } from '@/components/icon';
import NotData from '@/components/NotData';
import PagesHeader from '@/components/pages-header';
import Tables from '@/components/tables/tables';
import TipDesc from '@/components/tipDesc/tipDesc';
import useModal from '@/hooks/use-modal/useModal';
import { useParams } from '@/router/hooks';
import { KnowCollection } from '@/types/know/know';

import ChangeExpiredTimeModal from '../../sub-pages/document/components/ChangeExpiredTimeModal';

const FreshKnowledge = () => {
  const modal = useModal('update', 'personnel', 'delete', 'edit');
  const [messageApi, contextHolder] = message.useMessage();
  const { appId = '', key = '0' } = useParams() as { appId: string; key: string };
  const [keys, setKeys] = React.useState(key);

  const [page, setPage] = useState(1);
  const [pageSize, setPageSize] = useState(10);
  const [searchText, setSearchText] = useState('');
  // 返回值
  const [freshData, setFreshData] = useState({
    list: [],
    total: 0,
  });
  const tableRef = useRef<HTMLDivElement>(null);
  const [docount, setDocount] = useState(0);
  const [qacount, setQacount] = useState(0);
  // table选中的数据idgetExpired
  const [tableSelectEdRows, setTableSelectEdRows] = useState<React.Key[]>([]);
  // 新增排序状态
  const [experiodSortOrder, setExperiodSortOrder] = useState<-1 | 1 | undefined>(undefined);
  const [currentCollection, setCurrentCollection] = useState<KnowCollection | null>(null);

  const [isExpired, setIsExpired] = useState(false);
  /**
   * @description: 表格多选
   * @return {*}
   */
  const rowSelection = {
    onChange: (newSelectedRowKeys: React.Key[]) => {
      setTableSelectEdRows(newSelectedRowKeys);
    },
  };

  /**
   * @description: 获取过期文档
   */
  const getExpiredList = async () => {
    try {
      const params: any = {
        page,
        pageSize,
        searchText,
        appId,
        offset: (page - 1) * pageSize,
        expType: 'file',
      };
      if (experiodSortOrder !== undefined) {
        params.sort = experiodSortOrder.toString();
      }
      const res = await knowService.getExpiredList(params);
      setFreshData({
        list: res.list,
        total: res.total,
      });
      setDocount(res.total);
      modal.personnel.close();
    } catch (error) {
      messageApi.error(error);
    } finally {
      modal.personnel.close();
    }
  };
  /**
   * @description: 获取过期问题
   */
  const getExpiredQuestionList = async () => {
    try {
      const params: any = {
        page,
        pageSize,
        searchText,
        appId,
        offset: (page - 1) * pageSize,
        expType: 'qa',
      };
      if (experiodSortOrder !== undefined) {
        params.sort = experiodSortOrder.toString();
      }
      const res = await knowService.getExpiredList(params);
      if (isExpired) {
        setFreshData({
          list: res.list,
          total: res.total,
        });
      }
      modal.personnel.close();
      setQacount(res.total);
    } catch (error) {
      messageApi.error(error);
    } finally {
      modal.personnel.close();
    }
  };

  useEffect(() => {
    if (isExpired) {
      if (keys === '0') {
        getExpiredList();
      } else {
        getExpiredQuestionList();
      }
    }
    modal.personnel.open();
  }, [page, pageSize, searchText, appId, keys, experiodSortOrder]);

  useEffect(() => {
    if (!isExpired) {
      getExpiredList();
      getExpiredQuestionList();
      setIsExpired(true);
    }
  }, []);

  /**
   * @description: 打开弹窗

  /**
   * @description: 切换Tabs
   * @param {string} key
   * @return {*}
   */
  const onChange = (key: string) => {
    setKeys(key);
    setPage(1);
    setPageSize(10);
    setSearchText('');
    setTableSelectEdRows([]);
  };

  /**
   * @description: Tabs选项
   * @return {*}
   */
  const items: TabsProps['items'] = [
    {
      key: '0',
      label: (
        <div className="text-sm">
          文档
          {docount > 0 && (
            <span
              // className="ml-2 inline-block h-5 rounded-full bg-@error-color px-1 text-center leading-5 text-white "
              className=" ml-2 inline-block h-5 rounded-full text-center leading-5 "
              // style={{ background: 'linear-gradient(180deg, #FF4646 0%, #FF8F62 100%)' }}
            >
              ({docount > 99 ? '99+' : docount})
            </span>
          )}
        </div>
      ),
    },
    {
      key: '1',
      label: (
        <div className="text-sm">
          FAQ文档
          {qacount > 0 && (
            <span className="ml-2 inline-block h-5 rounded-full text-center leading-5 ">
              ({qacount > 99 ? '99+' : qacount})
            </span>
          )}
        </div>
      ),
    },
  ];

  /**
   * 处理 experiodDays 排序点击
   */
  const handleExperiodSortClick = () => {
    setExperiodSortOrder((prev) => {
      if (prev === undefined) return -1;
      if (prev === -1) return 1;
      return undefined;
    });
    setPage(1); // 排序时重置到第一页
  };

  /**
   * 渲染 experiodDays 排序表头
   */
  const renderExperiodSortTitle = () => (
    <span
      className="inline-flex cursor-pointer select-none items-center"
      onClick={handleExperiodSortClick}
    >
      过期时间
      <span className="ml-1 flex flex-col text-xs leading-none">
        <CaretUpOutlined
          style={{
            color: experiodSortOrder === 1 ? '#1677ff' : '#bfbfbf',
            fontSize: 10,
            marginBottom: -2,
          }}
        />
        <CaretDownOutlined
          style={{
            color: experiodSortOrder === -1 ? '#1677ff' : '#bfbfbf',
            fontSize: 10,
            marginTop: -2,
          }}
        />
      </span>
    </span>
  );

  const expiredColumns = [
    {
      title: '文件名',
      dataIndex: 'name',
      key: 'name',
      render: (text: string) => (
        <div className="w-[800px] truncate" title={text}>
          {text}
        </div>
      ),
    },
    {
      title: <div>文档所属</div>,
      width: '15%',
      dataIndex: 'datasetName',
      key: 'datasetName',
    },
    {
      title: renderExperiodSortTitle(),
      width: '20%',
      dataIndex: 'experiodDays',
      key: 'experiodDays',
      render: (text: string) => {
        if (text.includes('已过期')) {
          const match = text.match(/(\d+(?:\.\d+)?)/);
          if (match && match.index !== undefined) {
            const start = text.slice(0, match.index);
            const num = match[0];
            const end = text.slice(match.index + num.length);
            return (
              <div>
                <span>{start}</span>
                <span className="text-@error-color">{num}</span>
                <span>{end}</span>
              </div>
            );
          }
          return <div className="text-@error-color">{text}</div>;
        }
        return <div>{text}</div>;
      },
    },
    {
      title: <div>操作</div>,
      width: '20%',
      key: 'operation',
      render: (_: KnowCollection, record: KnowCollection) => (
        <div className=" flex gap-2">
          <Button
            size="small"
            type="text"
            onClick={() => {
              modal.update.open();
              setCurrentCollection(record);
            }}
          >
            <span className="flex items-center text-primary">
              <SvgIcon icon="message-ic22" size="20" className="mr-1" />
              修改过期时间
            </span>
          </Button>
          <Popconfirm
            title={`您确定要删除文件 ${record.name} 吗?`}
            onConfirm={() => {
              delExpireCollection(record);
            }}
            okText="删除"
            cancelText="取消"
          >
            <Button size="small" type="text">
              <span className="flex items-center text-error">
                <SvgIcon icon="message-ic3" size="20" className="mr-1" />
                删除
              </span>
            </Button>
          </Popconfirm>
        </div>
      ),
    },
  ];

  const delExpireCollection = async (item?: KnowCollection) => {
    try {
      const ids = item ? [item._id] : (tableSelectEdRows as string[]);
      if (!ids || ids.length === 0) {
        message.info('请选择要删除的项');
        return;
      }
      await datasetService.deleteDatasetFile({
        ids,
      });
      message.success('删除成功');
      setTableSelectEdRows([]); // 删除后清空选择
      if (keys === '0') {
        getExpiredList();
      } else {
        getExpiredQuestionList();
      }
    } catch (error) {
      console.error(error);
    }
  };
  const changeExpiredTimeConfirm = async (expiredTime: string) => {
    try {
      await knowService.postUpdateExpired({
        collection_id: currentCollection?._id as string,
        expired_time: expiredTime,
      });
      message.success('修改成功');
      modal.update.close();
      if (keys === '0') {
        getExpiredList();
      } else {
        getExpiredQuestionList();
      }
    } catch (error) {
      console.error(error);
    }
  };

  return (
    <div className="flex h-full flex-col bg-white">
      {contextHolder}
      <PagesHeader>
        知识新鲜度
        <TipDesc
          title="自动评估知识库中文档的有效期及过期状态，并支持将过期文档交由用户进行延期处理。"
          className="!my-0"
        />
      </PagesHeader>
      <div className=" flex flex-1 flex-col rounded-default  px-5">
        <div className=" ">
          <AntdTabs defaultActiveKey={key} items={items} onChange={onChange} />
        </div>
        <div className=" mb-[16px] flex items-center justify-between ">
          <div>
            <Search
              value={searchText}
              onChange={(e: any) => {
                // 拿到搜索的数据
                setSearchText(e.target.value);
              }}
              placeholder="请输入内容"
            />
          </div>
          <div className="flex items-center gap-2">
            {tableSelectEdRows.length > 0 && (
              <>
                <div className="w-[80px]">
                  {tableSelectEdRows && <span>已选择{tableSelectEdRows.length}项</span>}
                </div>

                {tableSelectEdRows.length > 0 && (
                  <Button
                    onClick={() => {
                      setTableSelectEdRows([]);
                    }}
                    color="default"
                    variant="outlined"
                    style={{
                      background: 'var(--fill-1)',
                      borderColor: 'var(--line-2)',
                      padding: '0 12px 0px 8px',
                    }}
                    icon={<CloseCircleOutlined />}
                  >
                    取消
                  </Button>
                )}
                <Button
                  danger
                  onClick={() => {
                    delExpireCollection();
                  }}
                  style={{
                    padding: '0 12px 0px 8px',
                  }}
                >
                  <SvgIcon icon="delete-outlined" size={16} />
                  删除
                </Button>
              </>
            )}
          </div>
        </div>
        {modal.personnel.isOpen ? (
          <Flex align="center" gap="middle" className="flex h-full items-center justify-center">
            <Spin size="large" />
          </Flex>
        ) : (
          <Content>
            {freshData.total > 0 ? (
              <div className="h-full flex-1 rounded-default  text-[#292D32]" ref={tableRef}>
                <Tables
                  rowSelection={{
                    type: 'checkbox',
                    ...rowSelection,
                    selectedRowKeys: tableSelectEdRows,
                  }}
                  rowKey="_id"
                  rowClassName="bg-[#F6F7FB]"
                  columns={expiredColumns}
                  dataSource={freshData.list}
                  pagination={false}
                  paginationProps={{
                    total: freshData.total,
                    current: page,
                    pageSize,
                    onChange: (page, pageSize) => {
                      setPage(page);
                      setPageSize(pageSize);
                    },
                  }}
                />
              </div>
            ) : (
              <NotData />
            )}
          </Content>
        )}
      </div>
      <ChangeExpiredTimeModal
        open={modal.update.isOpen}
        defaultDate={dayjs().add(0, 'day').format('YYYY-MM-DD 23:59:59')}
        onCancel={modal.update.close}
        onConfirm={changeExpiredTimeConfirm}
      />
    </div>
  );
};

export default FreshKnowledge;
